//
//  WBComposeViewController.swift
//  Weibo
//
//  Created by cc on 10/31/17.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 撰写微博控制器
/*
     加载视图控制器的时候， 如果xib和控制器同名，默认的构造函数会优先加载xib
 */
class WBComposeViewController: UIViewController {

    
    /// 文本编辑视图
    @IBOutlet weak var textView: WBComposeTextView!
    
    /// 底部工具栏
    @IBOutlet weak var toolBar: UIToolbar!
    
    /// 发布按钮
    @IBOutlet var sendButton: UIButton!
    
    /// 标题标签 - 换行的热键 option + Enter
    // 逐行选中文本并且设置属性
    // 如果要想调整行高间距，可以增加一个空行，设置空行的字体lineHeight
    @IBOutlet var titleLabel: UILabel!
    /// 工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    ///表情输入视图
    lazy var emoticonView: CZEmoticonInputView = CZEmoticonInputView.inputView {[weak self](emoticon) in
        self?.textView.insertEmoticon(em: emoticon)
    }
    
    
    
    
    // MARK: -生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        //强行更新约束
//        view.layoutIfNeeded()
        
        setupUI()
        
        //监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChange), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //激活键盘
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //关闭键盘
        textView.resignFirstResponder()
    }
    
    
    //MARK: 键盘监听方法
    @objc private func keyboardChange(n: Notification) {
        //1. 目标rect
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else {
            return
        }
        
        
        //2.设置底部约束的高度
        let offset = view.bounds.height - rect.origin.y
        
        //3.更新底部约束
        toolbarBottomCons.constant = offset
        
        //4.动画更新约束
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
        
        
    }
    

    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: -按钮监听方法
    //发布微博
    @IBAction func postStatus() {
        //1.获取发送给服务器的表情微博文字
        let text = textView.emoticonText
        
        print(text)
        
        //2.发布微博
        // FIXME : 测试发布图片的微博
//        let image = UIImage(named: "123.png")
        let image: UIImage? = nil
        WBNetworkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in
            
            //修改样式
            SVProgressHUD.setDefaultStyle(.dark)
            
            let message = isSuccess ? "发布成功" : "发布失败"
            
            SVProgressHUD.showInfo(withStatus: message)
            
            //如果成功，延迟一段时间关闭当前窗口
            if isSuccess {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
        
                    //恢复样式
                    SVProgressHUD.setDefaultStyle(.light)
                    self.close()
                })
            }
            
        }
        
    }
    
    
//    lazy var sendButton: UIButton = {
//        let btn = UIButton()
//        btn.setTitle("发布", for: [])
//        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//
//        // 设置标题颜色
//        btn.setTitleColor(UIColor.white, for: [])
//        btn.setTitleColor(UIColor.gray, for: .disabled)
//
//        //设置背景图片
//        btn.setBackgroundImage(UIImage(named: "compose_guide_button_default"), for: [])
//        btn.setBackgroundImage(UIImage(named: "compose_guide_button_check"), for: .highlighted)
//        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
//
//        //设置大小
//        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
//
//        return btn
//    }()
    
    
    //切换表情键盘
    @objc private func emoticonKeyboard() {
        //textView.inputView 是文本框的输入视图
        // 如果使用系统默认的键盘， 输入视图为nil
        //1> 测试键盘视图
//        let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 258))
//        keyboardView.backgroundColor = UIColor.blue
        //2> 设置键盘视图
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        
        //3> 刷新键盘视图
        textView.reloadInputViews()
    }
    
    
    
}



// MARK: - UITextViewDelegate
/*
    通知： 一对多， 只要有注册的监听者，在注销监听之前，都可以接收到通知
    代理： 一对一，最后设置的代理对象用效，前面设置的被覆盖
 
    苹果日常开发中， 代理的监听方式是最多的
  - 代理是发生事件时，直接让代理执行协议方法
    代理的效率高， 直接反向传值
 
  - 通知是发生事件时，将通知发送给通知中心， 通知中心再`广播`通知
    通知效率相对低一些，如果层次嵌套非常深，可以使用通知传值
 
 */
extension WBComposeViewController: UITextViewDelegate {
    
    
    /// 文本视图文字变化
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
    }
}



private extension WBComposeViewController {
    func setupUI() {
        view.backgroundColor = UIColor.white
        setupNavigationBar()
        setupToolbar()
    }
    
    
    /// 设置工具栏
    func setupToolbar() {
        
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        //遍历数组
        for s in itemSettings {
            
            guard let imageName = s["imageName"] else {
                continue
            }
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName+"_highlighted")
            
            
            let btn = UIButton()
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            
            //判断actionName
            if let actionName = s["actionName"] {
                //给按钮添加监听方法
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            
            //追加按钮
            items.append(UIBarButtonItem(customView: btn))
            
            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
           
        }
           //删除末尾弹簧
        items.removeLast()
        toolBar.items = items
    }
    
    
    
    /// 设置导航栏
    func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action:#selector(close))
        
        //设置发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        //设置标题视图
        navigationItem.titleView = titleLabel
        sendButton.isEnabled = false
    }
}






